package me.helllp.dake.generator.engine.service;

import com.google.common.io.Files;
import freemarker.template.TemplateException;
import lombok.Getter;
import lombok.Setter;
import me.helllp.dake.generator.config.GeneratorEngineConfiguration;
import me.helllp.dake.generator.engine.AbstractGenerator;
import me.helllp.dake.generator.config.enums.ProjectTypeEnum;
import me.helllp.dake.generator.meta.ProjectMetaData;
import me.helllp.dake.generator.utils.FileAndPathUtils;
import me.helllp.dake.generator.utils.YamlParser;
import org.apache.commons.collections4.MapUtils;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Getter
@Setter
public class ConfigurationGenerator extends AbstractGenerator {
    private Map<String, Object> properties;

    private ProjectMetaData projectMetaData;

    public ConfigurationGenerator(ProjectMetaData projectMetaData) {
        this.projectMetaData = projectMetaData;
    }

    @Override
    public void initGenerator(GeneratorEngineConfiguration engineConfiguration) throws TemplateException, IOException, InvocationTargetException, IllegalAccessException {
        super.initGenerator(engineConfiguration);
        properties = projectMetaData.getConfigMaps();
    }

    @Override
    public void generator() throws IOException {
        if (!MapUtils.isEmpty(properties)) {
            String fileName =
                    this.getProjectMetaData().getProjectType() == ProjectTypeEnum.MICRO_SERVICE ? "bootstrap.yml" : "application.yml";

            String context = YamlParser.flattenedMapToYaml(properties);
            Files.write(context.getBytes(StandardCharsets.UTF_8),
                    FileAndPathUtils.pathAppend(this.getProjectMetaData().getSrcResourcePath(), fileName));
        }
    }
}
